//
//  UIOAuthViewController.swift
//  阿恺微博
//
//  Created by 孙嘉恺 on 16/10/8.
//  Copyright © 2016年 孙嘉恺. All rights reserved.
//

import UIKit

let appKey = "1615379287"
let appSecrect = "c6f55e82fcfd01d942e91173d4fc7158"
let redirectURI = "http://www.zhihu.com"


class OAuthViewController: UIViewController {

    lazy var webview: UIWebView = {
        let webView = UIWebView(frame: self.view.bounds)
        webView.delegate = self
        return webView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webview)
        loadLoginPage()
    }
}

extension OAuthViewController {
    func loadLoginPage () {
        //1. 创建url
        let url = URL(string: NetworkTool.shared.oAuthURL)

        //2. 创建request
        let request = URLRequest(url: url!)
        
        //3. 发起request请求

        webview.loadRequest(request)
    }
}

extension OAuthViewController: UIWebViewDelegate {
    //1. webview理解成一个容器, 容器里面装网页
    //2. 每个网页对应一个url
    //3. 网页和网页之间可以跳转
    //4. 授权成功之后, 页面会从登录页面跳转到 百度 页面, code会附在百度的页面的url的后面.
    //5. 如果不想让某个网页显示, return false, 否则return no
    
    //是否允许加载页面
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.url?.absoluteString)
        //拿到绝对路径（可选值）
        let urlString = request.url?.absoluteString
        //1> 获取code
        //判断url是否有百度的前缀,如果有,则说明点击的是授权或取消按钮
        if let urlString = urlString, urlString.hasPrefix(redirectURI) {
            //判断是授权,还是取消: 如果url中有code, 说明是授权,否则是取消
            //https://www.baidu.com/?code=140db540622297a83821a49c8952a54e
            
            //query = request.url?.query, 获取url中参数的部分的字符串
            
            if let query = request.url?.query, query.hasPrefix("code=") {
                //说明点击的是授权按钮, 拿到code
                let code = query.substring(from: "code=".endIndex)
                
                print("点击了授权按钮, code是 \(code)")
                
                //2> 获取accessToken
                NetworkTool.shared.requestAccessToken(code: code, callBack: { (accesTokenResponse) in
                    
                    //3> 拿到access_token和uid, 获取用户信息
                    
                    /*
                     // accesTokenResponse 是Any类型, 所以需要做一个类型转换
                     // as? 可能换成功,可能转换不成功, 返回一个可选值
                     let acessDic = accesTokenResponse as? [String: Any]
                     // 可选绑定, var代表accesTokenDic可变
                     if var accesTokenDic = acessDic {
                     
                     }
                     */
                    
                    if var accesTokenDic = accesTokenResponse as? [String: Any], let uid =  accesTokenDic["uid"] as? String, let accessToken = accesTokenDic["access_token"] as? String {
                        
                        NetworkTool.shared.reqeustUserInfo(uid: uid, access_token: accessToken, callBack: { (userInfoDic) in
                            print(userInfoDic)
                            //4> 保存用户信息和accessToken的信息, 把两个字典合并
                            if let userInfoDic = userInfoDic as? [String: Any] {
                                for (key, value) in userInfoDic {
                                    accesTokenDic[key] = value
                                }
                            }
                            
                            //2. 保存
                            
                            //3. 创建一个User的类, 这个User类的功能包括: 1. 存储userInfo的dict,2. 从UserDefalut读取dict, 用来初始化单例, 3. 判断用户是否已经登录了;
                        })
                    }
                    
                })
            } else {
                print("点击了取消按钮")
            }
            return false
        }
        
        return true
    }
    
    //页面加载成功
    func webViewDidFinishLoad(_ webView: UIWebView) {
        let jsString = "document.getElementById('userId').value='sjkjz007@qq.com';document.getElementById('passwd').value='needsecret1124'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
}
